import globalData, {BodyTypeEnums} from "@/plugins/data";
import globalMethods from "@/plugins/methods";
import api from "@/api";

/*在线编辑类流版签*/
export default class BaseOffice {

  /**
   * 查看原文档
   * @param bodyType
   * @param userId
   * @param zwIframe
   * @return {Promise<void>}
   */

  async viewOffice({bodyType, userId, zwIframe}) {
    let transParams = this.getTransParams(zwIframe);
    if (transParams) {
      let canUseWebOffice = zwIframe.OfficeUtils.canUseWebOffice();
      if ((zwIframe.useWebOffice && canUseWebOffice)||bodyType=='45') {
        this.setOfficeStyle(zwIframe)
        await this.view(transParams, zwIframe);
      }else {
        await (zwIframe.OfficeAPI.showOffice({
          ...transParams,
          handWriteCurrentUserId: userId,
          editType:"0,0",
          officecanSaveLocal : transParams.officecanPrint, // 协同打印和另存为权限一致
        }));
        if(zwIframe?.OfficeAPI?.officeType === "wps"){
          zwIframe.OfficeAPI.activeOfficeOcx();
        }
      }
    }
  }


  /**
   * 转换开启时候的编辑方式
   * @param zwIframe
   * @param transParams
   * @param userId
   * @return {Promise<void>}
   */

  async editOfficeTrans({zwIframe, transParams, userId}) {
    await zwIframe.OfficeAPI.showOffice({
      ...transParams,
      handWriteCurrentUserId: userId,
      editType: "2,0",
      officecanPrint: true,
      officecanSaveLocal: true,
      //协同
      category: "1",
      showMode: 2, // kgApp模式，先隐藏显示
      wpsPopupFlag: "N", //使用静默模式不主动弹出
    })
  }

  /**
   * 转换关闭时候的开启方式
   * @param zwIframe
   * @return {Promise<void>}
   */
  async editNoOfficeTrans({zwIframe}) {
    await zwIframe.OfficeAPI.initOffice({
      targetDom: zwIframe.document.getElementById('officeFrameDiv'),
      viewMode: 'edit',
      editType: "2,0",
      category: "1",
    })
  }

  /**
   * 签章校验
   * @param fileId
   * @param originalFileId
   * @return {Promise<boolean>}
   */
  async validateSignature({fileId, originalFileId = ''}) {
    let validate = await api.commonValidateSignature(fileId, originalFileId);
    if (!validate) {
      console.log('commonValidateSignature', validate);
      globalMethods.warning({
        title: globalMethods.i18n('common.system.hint.label'),
        content: globalMethods.i18n('collaboration.alert.CantModifyBecauseOfIsignature'),
      });
      return false;
    }
    return true;
  }

  /**
   * 编辑功能
   * @param bodyType
   * @param userId
   * @param zwIframe
   * @param canSign
   * @return {Promise<void>}
   */
  async editOffice({bodyType, userId, zwIframe, canSign}) {
    let useWebOffice = zwIframe.useWebOffice && zwIframe.OfficeUtils.canUseWebOffice();
    if (useWebOffice) {
      let backendMethod = window.callBackendMethod("colManager", "readLock", globalData.summaryId);
      if (backendMethod.success !== true) {
        const {lockInfo} = backendMethod || {}
        if (lockInfo?.owner !==userId){
          globalMethods.warning({
            title: globalMethods.i18n('common.system.hint.label'),
            content: backendMethod.msg
          });
          return;
        }
      }
    }
    zwIframe.document.getElementById('viewState').value = '1';
    let transParams = this.getTransParams(zwIframe);
    if (transParams) {
      if (zwIframe.OfficeAPI?.officeType === 'weboffice' || window.top.wpsCanUseSlient) {
        this.setOfficeStyle(zwIframe);
        //签章的判断
        if (!await this.validateSignature({...transParams, zwIframe})) {
          return;
        }
        //用转换的方式打开
        await this.editOfficeTrans({zwIframe, transParams, userId, canSign})
        this.setOfficeUpdateFlag();
      }else{
        await zwIframe.OfficeAPI.fullSize(true);
      }
      return;
    }
    // if (bodyType!==BodyTypeEnums.pdf){
    if (useWebOffice) {
      //签章的判断
      if (!await this.validateSignature({...zwIframe.OfficeAPI.options, zwIframe})) {
        return;
      }
      //无转换编辑
      await this.editNoOfficeTrans({zwIframe, canSign});
      this.setOfficeUpdateFlag();
    }else {
      await zwIframe.OfficeAPI.loadOffice(false);
    }
    // }
  }


  /**
   * 查看原文档
   * @param transParams
   * @param zwIframe
   * @return {Promise<void>}
   */
  async view(transParams, zwIframe) {
    transParams.targetDom = zwIframe.document.getElementById('officeFrameDiv');
    transParams.category = "4";
    await zwIframe.OfficeAPI.initOffice(transParams);
  }

  /**
   * 提取转换参数
   * @param ctx
   * @return {*}
   */
  getTransParams(ctx) {
    let officeParamDiv = ctx.document.querySelector('.officeparam');
    if (!officeParamDiv) {
      return;
    }
    officeParamDiv.setAttribute('style', '');
    let officeParamStr = officeParamDiv.getAttribute('param');
    if (officeParamStr) {
      let text = `{${officeParamStr}}`;
      let officeParamJson = $.parseJSON(text);
      console.log('officeParamJson', officeParamJson);
      return officeParamJson;
    }
  }

  /**
   * 签章
   * @return {Promise<Boolean>}
   */
  async signature({zwIframe}) {
    let check = zwIframe.getOfficePluginsSettings && zwIframe.canUseWebOffice && zwIframe.useWebOffice;
    if(!check){
      return false;
    }
    let settings = zwIframe.getOfficePluginsSettings();
    if (settings?.webOfficeConfig?.enabled) {
      let newVar = await zwIframe.OfficeUtils.webofficeSignatureJudgment();
      if (newVar){
        settings.webOfficeConfig.enabled = false;
        zwIframe.canUseWebOffice = false;
        zwIframe.setOfficePluginsSettings && zwIframe.setOfficePluginsSettings(settings);
        return true;
      }
    }
    return false;
  }

  /**
   * 设置转换的样式
   * @param ctx
   */
  setOfficeStyle(ctx) {
    let officeTransDom = ctx.document.getElementById('officeTransIframe');
    officeTransDom && officeTransDom.remove();
    let element = ctx.document.getElementById('officeFrameDiv');
    if (element) {
      element.style.height = '100%';
      element.style.width = '100%';
    }
  }
  
  setOfficeUpdateFlag(){
    //0 ： 没有做修改, 1:修改了正文   2：修改了附件 3 ： 修改了正文和附件
    if (window.isEditAttOrContent === 2) {
      window.isEditAttOrContent = 3;
    } else {
      window.isEditAttOrContent = 1;
    }
  }
  

}
